package com.xmall.exception;

import com.alibaba.nacos.shaded.com.google.common.base.Joiner;
import com.xmall.define.base.Result;
import com.xmall.define.base.ResultCode;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 参数校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("methodArgumentNotValidException: {}", e.getMessage());
        List<String> errors = new ArrayList<>();
        e.getBindingResult().getAllErrors().forEach(error -> {
            String errorMessage = error.getDefaultMessage();
            errors.add(errorMessage);
        });
        return Result.error(Joiner.on(", ").join(errors));
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler(value = XmallException.class)
    public Result xmallException(XmallException e){
        log.error("xmallException: {}", e.getMessage());
        return Result.error(e.getCode(), e.getMessage(), e.getData());
    }

    /**
     * Feign异常
     */
    @ExceptionHandler(value = FeignException.class)
    public Result feignException(FeignException e){
        // 认证异常
        if(e instanceof FeignException.Unauthorized){
            return Result.error(ResultCode.NOT_LOGIN);
        }
        log.error("FeignException: {}", e.getMessage());
        return Result.error();
    }

    /**
     * 权限异常
     */
    @ExceptionHandler(value = AccessDeniedException.class)
    public Result accessDeniedException(AccessDeniedException e){
        log.error("AccessDeniedException: {}", e.getMessage());
        return Result.error(ResultCode.PERMISSION_DENIED);
    }

    /**
     * 其他异常
     */
    @ExceptionHandler(value = Exception.class)
    public Result exception(Exception e){
        log.error("OtherException: {}", e.getMessage());
        return Result.error();
    }
}
